package com.woniuxy.stall.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.certified.dao.CertifiedInfo;
import com.woniuxy.certified.model.param.LoadAllAccountParam;
import com.woniuxy.core.exception.accountException.AccountException;
import com.woniuxy.core.exception.accountException.AccountExceptionCode;
import com.woniuxy.core.exception.certifiedException.CertifiedException;
import com.woniuxy.core.exception.certifiedException.CertifiedExceptionCode;
import com.woniuxy.core.exception.orderException.OrderException;
import com.woniuxy.core.exception.orderException.OrderExceptionCode;
import com.woniuxy.core.exception.stallException.StallException;
import com.woniuxy.core.exception.stallException.StallExceptionCode;
import com.woniuxy.core.model.GetOrdersByStallIdAndTimeForm;
import com.woniuxy.core.model.Result;
import com.woniuxy.core.staticCode.StallInfoCode;
import com.woniuxy.core.staticCode.StallTypeCode;
import com.woniuxy.core.util.OSSUtil;
import com.woniuxy.core.util.PageInfo;
import com.woniuxy.order.dao.OrderInfo;
import com.woniuxy.renters.dao.RentersInfo;
import com.woniuxy.renters.model.param.AddrentersinsertstallParam;
import com.woniuxy.stall.dao.StallCheck;
import com.woniuxy.stall.dao.StallInfo;
import com.woniuxy.stall.dto.CertifiedAccount;
import com.woniuxy.stall.feign.CertifiedClient;
import com.woniuxy.stall.feign.OrderClient;
import com.woniuxy.stall.feign.RentersClient;
import com.woniuxy.stall.feign.UserClient;
import com.woniuxy.stall.mapper.StallCheckMapper;
import com.woniuxy.stall.mapper.StallInfoMapper;
import com.woniuxy.stall.model.Param.SelectStallRentByCertifiedIdParam;
import com.woniuxy.stall.model.form.SelectStallForm;
import com.woniuxy.stall.service.StallInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.stall.service.StallRentTimeService;
import com.woniuxy.stall.service.impl.dto.StallInfoDTO;
import com.woniuxy.stall.service.param.*;
import com.woniuxy.user.dao.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.URI;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 凌玉春
 * @since 2024年01月15日
 */
@Service
public class StallInfoServiceImpl extends ServiceImpl<StallInfoMapper, StallInfo> implements StallInfoService {
    @Autowired
    private StallInfoMapper stallInfoMapper;
    @Autowired
    private StallRentTimeService stallRentTimeService;
    @Autowired
    private CertifiedClient certifiedClient;
    @Autowired
    private RentersClient rentersClient;
    @Autowired
    private OrderClient orderClient;
    @Autowired
    private UserClient userClient;

    @Resource
    private OSSUtil ossUtil;

    @Autowired
    private StallCheckMapper stallCheckMapper;

    public StallInfo findStallById(Integer stallInfoId) {
        StallInfo stallInfo = stallInfoMapper.selectById(stallInfoId);
        if (stallInfo==null) throw new StallException(StallExceptionCode.STALL_NOT_EXIST);
        if (stallInfo.getStallUpDownState()== StallInfoCode.STALL_DOWN.getCode()){
            throw new StallException(StallExceptionCode.STALL_IS_DOWN);
        }
        return stallInfo;
    }

    public String findStallNumById(Integer stallInfoId) {
        StallInfo stallInfo = stallInfoMapper.selectById(stallInfoId);
        if (stallInfo==null) throw new StallException(StallExceptionCode.STALL_NOT_EXIST);
        String stallInfoNum = stallInfo.getStallInfoNum();
        return stallInfoNum;
    }

    public PageInfo<StallInfo> findStallsByCertifiedId(SelectStallForm ssf) {
        QueryWrapper<StallInfo> wrapper = new QueryWrapper<StallInfo>();
        wrapper.eq("certified_info_id",ssf.getCertifiedId());
        wrapper.eq("stall_check_state",StallInfoCode.STALL_CHECK_SUCCESS.getCode());
        //车位类型
        if(ssf.getStallTpye()!=null){
            wrapper.eq("stall_tpye",ssf.getStallTpye());
        }
        //车位上下架状态
        if(ssf.getStallUpDownState()!=null){
            wrapper.eq("stall_up_down_state",ssf.getStallUpDownState());
        }
        //车位使用状态
        if(ssf.getStallUseState()!=null){
            wrapper.eq("stall_use_state",ssf.getStallUseState());
        }
        //车位号
        if(ssf.getStallInfoNum()!=null&&!ssf.getStallInfoNum().equals("")){
            wrapper.like("stall_info_num",ssf.getStallInfoNum());
        }
        wrapper.orderByDesc("stall_info_id");
        Page<StallInfo> page = new Page<StallInfo>(ssf.getPageNum()==null?1:ssf.getPageNum(), ssf.getPageSize()==null?5:ssf.getPageSize());
        Page<StallInfo> stallInfoPage = stallInfoMapper.selectPage(page, wrapper);
        PageInfo pageInfo = BeanUtil.toBean(stallInfoPage, PageInfo.class);
        pageInfo.setList(stallInfoPage.getRecords());
        pageInfo.setPages(page.getPages());
        return pageInfo;
    }

    public List<Integer> certifiedAddStall(List<AddStallParam> params) {
        AddStallParam pm = params.get(0);
        Integer certifiedId = pm.getCertifiedInfoId();
//        Result<CertifiedAccount> certifiedAccountResult = certifiedClient.findCertifiedAccountById(certifiedId);
//        CertifiedAccount certifiedAccount = certifiedAccountResult.getData();
//        if (certifiedAccount==null) throw new CertifiedException(CertifiedExceptionCode.ACCOUNT_INEXISTENCE);
//        Integer certifiedInfoId = certifiedAccountResult.getData().getCertifiedInfoId();
        List<Integer> stallInfoIds=new ArrayList<>();
        for (AddStallParam param : params) {
            System.out.println("param:"+param);
            QueryWrapper<StallInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("stall_info_num",param.getStallInfoNum());
            wrapper.eq("certified_info_id",param.getCertifiedInfoId());
            StallInfo one = stallInfoMapper.selectOne(wrapper);
            if (one!=null) throw new StallException(StallExceptionCode.STALL_ALREADY_HAVE);
            StallInfo stallInfo = BeanUtil.toBean(param, StallInfo.class);
            stallInfo.setStallInfoAffiliation(param.getStallInfoAffiliation());
            stallInfo.setCertifiedInfoId(certifiedId);
            stallInfo.setStallUseState(StallInfoCode.STALL_ON_FREE.getCode());
            stallInfo.setStallUpDownState(StallInfoCode.STALL_DOWN.getCode());
            stallInfo.setStallCheckState(StallInfoCode.STALL_CHECK_SUCCESS.getCode());
            stallInfoMapper.insert(stallInfo);
            System.out.println("=======");
            System.out.println(stallInfo.getStallInfoId());
            Integer stallInfoId = stallInfo.getStallInfoId();
            stallInfoIds.add(stallInfoId);
        }
        return stallInfoIds;

    }

    public PageInfo getWaitingCheckStall(Integer current,Integer size) {
        Page page=new Page(current,size);
        QueryWrapper<StallInfo> wrapper = new QueryWrapper<StallInfo>();
        wrapper.eq("stall_check_state",StallInfoCode.STALL_WAITING_CHECK.getCode());
        Page selectPage = stallInfoMapper.selectPage(page, wrapper);
        PageInfo pageInfo = BeanUtil.toBean(selectPage, PageInfo.class);
        pageInfo.setPages(selectPage.getPages());
        pageInfo.setList(selectPage.getRecords());
        return pageInfo;
    }

    public void checkStall(Set<Integer> ids) {
        QueryWrapper<StallInfo> wrapper = new QueryWrapper<StallInfo>();
        wrapper.in("stall_info_id",ids);
        wrapper.eq("stall_check_state",StallInfoCode.STALL_WAITING_CHECK.getCode());
        List<StallInfo> infos = stallInfoMapper.selectList(wrapper);
        if (infos==null){
            throw new StallException(StallExceptionCode.STALL_NONE_OR_CHECKED);
        }
        UpdateWrapper<StallInfo> updateWrapper = new UpdateWrapper<StallInfo>();
        updateWrapper.in("stall_info_id",ids);
        updateWrapper.set("stall_check_state",StallInfoCode.STALL_CHECK_SUCCESS.getCode());
        stallInfoMapper.update(null,updateWrapper);

    }

    public PageInfo<StallInfo> getWaitingCheckStallByCeId(Integer current, Integer size, Integer certifiedId) {
        Page page=new Page(current,size);
        QueryWrapper<StallInfo> wrapper = new QueryWrapper<StallInfo>();
        wrapper.eq("stall_check_state",StallInfoCode.STALL_WAITING_CHECK.getCode());
        wrapper.eq("certified_info_id",certifiedId);
        Page selectPage = stallInfoMapper.selectPage(page, wrapper);
        PageInfo pageInfo = BeanUtil.toBean(selectPage, PageInfo.class);
        pageInfo.setPages(selectPage.getPages());
        pageInfo.setList(selectPage.getRecords());
        return pageInfo;
    }

    public PageInfo<StallInfoDTO> platGetStalls(PlatGetStallParam param) {
        Integer current=param.getCurrent()==null?1:param.getCurrent();
        Integer size=param.getSize()==null?3:param.getSize();
        Page<StallInfo> page=new Page(current,size);
        QueryWrapper<StallInfo> wrapper = new QueryWrapper<StallInfo>();
        Page<StallInfo> stallInfoPage = stallInfoMapper.selectPage(page, wrapper);
        List<StallInfo> records = stallInfoPage.getRecords();
        StallInfoCode[] values = StallInfoCode.values();
        List<StallInfoDTO> dtos=new ArrayList<StallInfoDTO>();
        Set<Integer> ids=new HashSet<>();
        for (StallInfo stallInfo : records) {
            Integer stallInfoId = stallInfo.getStallInfoId();
            ids.add(stallInfoId);
        }
        for (StallInfo stallInfo : records) {
            StallInfoDTO stallInfoDTO = BeanUtil.toBean(stallInfo, StallInfoDTO.class);
            Result<List<OrderInfo>> listResult = orderClient.getOrderInfosByStallIds(ids);
            List<OrderInfo> orderInfoList = listResult.getData();
            for (OrderInfo orderInfo : orderInfoList) {
                if (orderInfo.getStatllInfoId()==stallInfo.getStallInfoId()){
                    LocalDateTime startTime = orderInfo.getStartTime();
                    LocalDateTime endTime = orderInfo.getEndTime();
                    LocalDateTime now = LocalDateTime.now();
                    if (now.isAfter(startTime)&&now.isBefore(endTime)){
                        stallInfoDTO.setStallUseState(StallInfoCode.STALL_ON_UES.getCode());
                        stallInfoDTO.setStateName(StallInfoCode.STALL_ON_UES.getMessage());
                        break;
                    }

                }
                stallInfoDTO.setStateName(StallInfoCode.STALL_ON_FREE.getMessage());
                stallInfoDTO.setStallUseState(StallInfoCode.STALL_ON_FREE.getCode());
            }
            for (StallInfoCode value : values) {
                if (value.getCode()== stallInfo.getStallUpDownState()){
                    stallInfoDTO.setUpDownStateName(value.getMessage());
                }
            }
            for (StallInfoCode value : values) {
                if (value.getCode()== stallInfo.getStallCheckState()){
                    stallInfoDTO.setCheckName(value.getMessage());
                }
            }
            Integer certifiedInfoId = stallInfoDTO.getCertifiedInfoId();
            Result<CertifiedInfo> certifiedInfoById = certifiedClient.findCertifiedInfoById(certifiedInfoId);
            CertifiedInfo certifiedInfo = certifiedInfoById.getData();
            String certifiedInfoName = certifiedInfo.getCertifiedInfoName();
            stallInfoDTO.setCertifiedName(certifiedInfoName);
            StallTypeCode[] codes = StallTypeCode.values();
            for (StallTypeCode stallTypeCode : codes) {
                if (stallTypeCode.getCode()== stallInfo.getStallTpye()){
                    stallInfoDTO.setTypeName(stallTypeCode.getMessage());

                }
            }
            Integer id = stallInfoDTO.getStallInfoAffiliation();
            if (id==StallInfoCode.STALL_OF_CERTIFIED.getCode()){
                stallInfoDTO.setAffiliationName(StallInfoCode.STALL_OF_CERTIFIED.getMessage());
            }else {
                stallInfoDTO.setAffiliationName("业主车位");
            }

            dtos.add(stallInfoDTO);
        }
        PageInfo pageInfo = BeanUtil.toBean(page, PageInfo.class);
        pageInfo.setPages(page.getPages());
        pageInfo.setList(dtos);
        return pageInfo;
    }

    public List<StallInfoDTO> renterGetStalls(Integer renterId) {
        Result<RentersInfo> result = rentersClient.getRentersInfoById(renterId);
        RentersInfo rentersInfo = result.getData();
        String idString = rentersInfo.getStallInfoId();
        JSONArray jsonArray = JSONUtil.parseArray(idString);
        List<Integer> stallInfoIds = jsonArray.toList(Integer.class);
        QueryWrapper<StallInfo> wrapper = new QueryWrapper<StallInfo>();
        wrapper.in("stall_info_id",stallInfoIds);
        List<StallInfo> stallInfos = stallInfoMapper.selectList(wrapper);
        StallInfoCode[] values = StallInfoCode.values();
        List<StallInfoDTO> dtos=new ArrayList<StallInfoDTO>();
        Result<List<OrderInfo>> listResult = orderClient.getOrderInfosByStallIds((Set<Integer>) stallInfoIds);
        List<OrderInfo> orderInfoList = listResult.getData();
        for (StallInfo stallInfo : stallInfos) {
            StallInfoDTO stallInfoDTO = BeanUtil.toBean(stallInfo, StallInfoDTO.class);
            for (OrderInfo orderInfo : orderInfoList) {
                if (orderInfo.getStatllInfoId()==stallInfo.getStallInfoId()){
                    LocalDateTime startTime = orderInfo.getStartTime();
                    LocalDateTime endTime = orderInfo.getEndTime();
                    LocalDateTime now = LocalDateTime.now();
                    if (now.isAfter(startTime)&&now.isBefore(endTime)){
                        stallInfoDTO.setStallUseState(StallInfoCode.STALL_ON_UES.getCode());
                        stallInfoDTO.setStateName(StallInfoCode.STALL_ON_UES.getMessage());
                        break;
                    }

                }
                stallInfoDTO.setStateName(StallInfoCode.STALL_ON_FREE.getMessage());
                stallInfoDTO.setStallUseState(StallInfoCode.STALL_ON_FREE.getCode());
            }
            for (StallInfoCode value : values) {
                if (value.getCode()== stallInfo.getStallUpDownState()){
                    stallInfoDTO.setUpDownStateName(value.getMessage());
                }
            }
            for (StallInfoCode value : values) {
                if (value.getCode()== stallInfo.getStallCheckState()){
                    stallInfoDTO.setCheckName(value.getMessage());
                }
            }
            Integer certifiedInfoId = stallInfoDTO.getCertifiedInfoId();
            Result<CertifiedInfo> certifiedInfoById = certifiedClient.findCertifiedInfoById(certifiedInfoId);
            CertifiedInfo certifiedInfo = certifiedInfoById.getData();
            String certifiedInfoName = certifiedInfo.getCertifiedInfoName();
            stallInfoDTO.setCertifiedName(certifiedInfoName);
            StallTypeCode[] codes = StallTypeCode.values();
            for (StallTypeCode stallTypeCode : codes) {
                if (stallTypeCode.getCode()== stallInfo.getStallTpye()){
                    stallInfoDTO.setTypeName(stallTypeCode.getMessage());

                }
            }
            Integer id = stallInfoDTO.getStallInfoAffiliation();
            if (id==StallInfoCode.STALL_OF_CERTIFIED.getCode()){
                stallInfoDTO.setAffiliationName(StallInfoCode.STALL_OF_CERTIFIED.getMessage());
            }else {
                stallInfoDTO.setAffiliationName("业主车位");
            }
            dtos.add(stallInfoDTO);
        }
        return dtos;
    }

    @Override
    public void downStallById(Integer renterId, Integer stallInfoId) {
        QueryWrapper<StallInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("stall_info_id",stallInfoId);
        StallInfo stallInfo = stallInfoMapper.selectOne(wrapper);
        if (stallInfo==null){
            throw new StallException(StallExceptionCode.STALL_NOT_EXIST);
        }
        if (stallInfo.getStallInfoAffiliation()!=StallInfoCode.STALL_OF_RENTER.getCode()){
            throw new StallException(StallExceptionCode.STALL_NOT_EXIST);
        }
        if (stallInfo.getStallCheckState()!=StallInfoCode.STALL_CHECK_SUCCESS.getCode()){
            throw new StallException(StallExceptionCode.STALL_CERTIFIED);
        }
        stallInfo.setStallUpDownState(StallInfoCode.STALL_DOWN.getCode());

        stallInfoMapper.updateById(stallInfo);
        stallRentTimeService.delTabByStallId(stallInfoId);
    }

    @Override
    public void upStallById(RenterUpStallByIdParam param) {
        Integer renterId = param.getRenterInfoId();
        Integer stallInfoId = param.getStallInfoId();
        String startTime = param.getStartTime();
        String endTime = param.getEndTime();
        QueryWrapper<StallInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("stall_info_id",stallInfoId);
        StallInfo stallInfo = stallInfoMapper.selectOne(wrapper);
        if (stallInfo==null){
            throw new StallException(StallExceptionCode.STALL_NOT_EXIST);
        }
        if (stallInfo.getStallInfoAffiliation()!=StallInfoCode.STALL_OF_RENTER.getCode()){
            throw new StallException(StallExceptionCode.STALL_CERTIFIED);
        }
        if(stallInfo.getStallUpDownState()==StallInfoCode.STALL_UP.getCode()){
            throw new StallException(StallExceptionCode.STALL_UPING);
        }
        stallInfo.setStallUpDownState(StallInfoCode.STALL_UP.getCode());
        stallInfoMapper.updateById(stallInfo);
        RenterUpStallEveryDayParam everyDayParam = BeanUtil.toBean(param, RenterUpStallEveryDayParam.class);
        stallRentTimeService.upStallEveryDay(everyDayParam);
    }

    @Override
    public List<StallInfo> getStallInfosByIds(Set<Integer> stallInfoIds) {
        QueryWrapper<StallInfo> wrapper = new QueryWrapper<>();
        wrapper.in("stall_info_id",stallInfoIds);
        List<StallInfo> stallInfos = stallInfoMapper.selectList(wrapper);
        if (stallInfos.size()!= stallInfoIds.size()){
            throw new StallException(StallExceptionCode.STALL_NONE_OR_CHECKED);
        }
        return stallInfos;
    }

    @Override
    public void cerDownStallById(Integer cerAccountId, Integer stallInfoId) {
        Result<CertifiedAccount> certifiedAccountResult = certifiedClient.findCertifiedAccountById(cerAccountId);
        CertifiedAccount certifiedAccount = certifiedAccountResult.getData();
        Integer certifiedInfoId = certifiedAccount.getCertifiedInfoId();
        Result<CertifiedInfo> certifiedInfoResult = certifiedClient.findCertifiedInfoById(certifiedInfoId);
        CertifiedInfo certifiedInfo = certifiedInfoResult.getData();
        StallInfo stallInfo = stallInfoMapper.selectById(stallInfoId);
        Integer stallCheckState = stallInfo.getStallCheckState();
        if (stallCheckState!=StallInfoCode.STALL_CHECK_SUCCESS.getCode()){
            throw new StallException(StallExceptionCode.STALL_NOT_CHECK);
        }
        Integer certifiedInfoId1 = stallInfo.getCertifiedInfoId();
        if (certifiedInfoId!=certifiedInfoId1){
            throw new StallException(StallExceptionCode.STALL_NOT_EXIST);
        }
        Integer stallInfoAffiliation = stallInfo.getStallInfoAffiliation();
        if (stallInfoAffiliation!=StallInfoCode.STALL_OF_CERTIFIED.getCode()){
            throw new StallException(StallExceptionCode.STALL_NOT_EXIST);
        }
        if(stallInfo.getStallUpDownState()==StallInfoCode.STALL_DOWN.getCode()){
            throw new CertifiedException(CertifiedExceptionCode.DO_NOT_REPEAT_OPERATION);
        }
        stallInfo.setStallUpDownState(StallInfoCode.STALL_DOWN.getCode());
        stallInfoMapper.updateById(stallInfo);
        stallRentTimeService.delTabByStallId(stallInfoId);
    }

    @Override
    public void cerUpStallById(CerUpStallByIdParam param) {
        Integer cerAccountId = param.getCerAccountId();
        Integer stallInfoId = param.getStallInfoId();
        String startTime = param.getStartTime();
        String endTime = param.getEndTime();
        StallInfo stallInfo = stallInfoMapper.selectById(stallInfoId);
        //是否存在该车位
        if (stallInfo==null){
            throw new StallException(StallExceptionCode.STALL_NOT_EXIST);
        }
        //是否已经定价

        //该车位是否已经上架
        if(stallInfo.getStallUpDownState()==StallInfoCode.STALL_UP.getCode()){
            throw new CertifiedException(CertifiedExceptionCode.DO_NOT_REPEAT_OPERATION);
        }
        Result<CertifiedAccount> certifiedAccountResult = certifiedClient.findCertifiedAccountById(cerAccountId);
        CertifiedAccount certifiedAccount = certifiedAccountResult.getData();
        Integer certifiedInfoId = certifiedAccount.getCertifiedInfoId();
        Integer certifiedInfoId1 = stallInfo.getCertifiedInfoId();
        if (certifiedInfoId!=certifiedInfoId1){
            throw new StallException(StallExceptionCode.STALL_NOT_EXIST);
        }
        stallInfo.setStallUpDownState(StallInfoCode.STALL_UP.getCode());
        stallInfoMapper.updateById(stallInfo);
        CerUpStallEveryDayParam everyDayParam = BeanUtil.toBean(param, CerUpStallEveryDayParam.class);
        everyDayParam.setCertifiedId(certifiedInfoId);
        Set<Integer> ids = new HashSet<>();
        ids.add(stallInfoId);
        everyDayParam.setStallInfoIds(ids);
        stallRentTimeService.cerUpStallEveryDay(everyDayParam);

    }

    @Override
    public PageInfo<StallInfoDTO> cerGetStallPage(CerGetStallPageParam param) {
        Integer certifiedAccountId = param.getCertifiedAccountId();
        Result<CertifiedAccount> certifiedAccountResult = certifiedClient.findCertifiedAccountById(certifiedAccountId);
        CertifiedAccount certifiedAccount = certifiedAccountResult.getData();
        Integer certifiedInfoId = certifiedAccount.getCertifiedInfoId();
        Result<CertifiedInfo> certifiedInfoById = certifiedClient.findCertifiedInfoById(certifiedInfoId);
        CertifiedInfo certifiedInfo = certifiedInfoById.getData();
        String certifiedInfoName = certifiedInfo.getCertifiedInfoName();
        QueryWrapper<StallInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("certified_info_id",certifiedInfoId);
        Integer checkState = param.getCheckState();
        if (checkState==StallInfoCode.STALL_CHECK_SUCCESS.getCode()){
            wrapper.eq("stall_check_state",StallInfoCode.STALL_CHECK_SUCCESS.getCode());
        } else if (checkState==StallInfoCode.STALL_CHECK_FAIL.getCode()) {
            wrapper.eq("stall_check_state",StallInfoCode.STALL_CHECK_FAIL.getCode());
        } else if (checkState==StallInfoCode.STALL_WAITING_CHECK.getCode()) {
            wrapper.eq("stall_check_state",StallInfoCode.STALL_WAITING_CHECK.getCode());
        }
        Integer useState = param.getUseState();
        if (useState==StallInfoCode.STALL_ON_UES.getCode()){
            wrapper.eq("stall_use_state",StallInfoCode.STALL_ON_UES.getCode());
        } else if (useState==StallInfoCode.STALL_ON_FREE.getCode()) {
            wrapper.eq("stall_use_state",StallInfoCode.STALL_ON_FREE.getCode());
        }
        Integer upDownState = param.getUpDownState();
        if (upDownState==StallInfoCode.STALL_UP.getCode()){
            wrapper.eq("stall_up_down_state",StallInfoCode.STALL_UP.getCode());
        } else if (upDownState==StallInfoCode.STALL_DOWN.getCode()) {
            wrapper.eq("stall_up_down_state",StallInfoCode.STALL_DOWN.getCode());
        }
        Page<StallInfo> page = new Page<>(param.getCurrent() == null ? 1 : param.getCurrent(), param.getSize() == null ? 3 : param.getSize());
        Page<StallInfo> stallInfoPage = stallInfoMapper.selectPage(page, wrapper);
        List<StallInfo> records = stallInfoPage.getRecords();
        StallInfoCode[] values = StallInfoCode.values();
        List<StallInfoDTO> dtos=new ArrayList<StallInfoDTO>();
        Set<Integer> ids=new HashSet<>();
        for (StallInfo record : records) {
            Integer stallInfoId = record.getStallInfoId();
            ids.add(stallInfoId);
        }
        Result<List<OrderInfo>> listResult = orderClient.getOrderInfosByStallIds(ids);
        List<OrderInfo> orderInfoList = listResult.getData();
        for (StallInfo stallInfo : records) {
            StallInfoDTO stallInfoDTO = BeanUtil.toBean(stallInfo, StallInfoDTO.class);
            for (OrderInfo orderInfo : orderInfoList) {
                if (orderInfo.getStatllInfoId()==stallInfo.getStallInfoId()){
                    LocalDateTime startTime = orderInfo.getStartTime();
                    LocalDateTime endTime = orderInfo.getEndTime();
                    LocalDateTime now = LocalDateTime.now();
                    if (now.isAfter(startTime)&&now.isBefore(endTime)){
                        stallInfoDTO.setStallUseState(StallInfoCode.STALL_ON_UES.getCode());
                        stallInfoDTO.setStateName(StallInfoCode.STALL_ON_UES.getMessage());
                        break;
                    }

                }
                stallInfoDTO.setStateName(StallInfoCode.STALL_ON_FREE.getMessage());
                stallInfoDTO.setStallUseState(StallInfoCode.STALL_ON_FREE.getCode());
            }
            for (StallInfoCode value : values) {
                if (value.getCode()== stallInfo.getStallUpDownState()){
                    stallInfoDTO.setUpDownStateName(value.getMessage());
                }
            }
            for (StallInfoCode value : values) {
                if (value.getCode()== stallInfo.getStallCheckState()){
                    stallInfoDTO.setCheckName(value.getMessage());
                }
            }
            stallInfoDTO.setCertifiedName(certifiedInfoName);
            StallTypeCode[] codes = StallTypeCode.values();
            for (StallTypeCode stallTypeCode : codes) {
                if (stallTypeCode.getCode()== stallInfo.getStallTpye()){
                    stallInfoDTO.setTypeName(stallTypeCode.getMessage());

                }
            }
            Integer id = stallInfoDTO.getStallInfoAffiliation();
            if (id==StallInfoCode.STALL_OF_CERTIFIED.getCode()){
                stallInfoDTO.setAffiliationName(StallInfoCode.STALL_OF_CERTIFIED.getMessage());
            }else {
                stallInfoDTO.setAffiliationName("业主车位");
            }

            dtos.add(stallInfoDTO);
        }
        PageInfo pageInfo = BeanUtil.toBean(page, PageInfo.class);
        pageInfo.setPages(page.getPages());
        pageInfo.setList(dtos);
        return pageInfo;
    }

    @Override
    public void rentersinsertstall(AddrentersinsertstallParam param) {
        Result<Boolean> booleanResult = rentersClient.loadAllRentersInfoss(String.valueOf(param.getUserId()));
        Boolean data = booleanResult.getData();
        if (!data){
            throw new AccountException(AccountExceptionCode.ID_NOT);
        }
        Result<RentersInfo> result = rentersClient.getRentersInfoById(param.getUserId());
        RentersInfo rentersInfo = result.getData();
        String rentersInfoCard = rentersInfo.getRentersInfoCard();
        String rentersInfoName = rentersInfo.getRentersInfoName();
        System.out.println("----------");
        System.out.println(rentersInfoCard);
        System.out.println(rentersInfoName);
        System.out.println(param.getUserId());
        System.out.println(param.getStall());
        System.out.println(param.getCertifiedInfoId());
        System.out.println(param.getNotes());
        System.out.println(param.getImage());
        System.out.println("----------");
        if (param.getStall()==null){
            throw  new AccountException(AccountExceptionCode.NOT_NULL);
        }
        if (param.getCertifiedInfoId()==null){
            throw  new AccountException(AccountExceptionCode.NOT_NULL);
        }
        if (param.getNotes()==null){
            throw  new AccountException(AccountExceptionCode.NOT_NULL);
        }
        if (param.getImage()==null){
            throw  new AccountException(AccountExceptionCode.NOT_NULL);
        }

        QueryWrapper<StallCheck> wrapper = new QueryWrapper<>();
        wrapper.eq("stall_info_num",param.getStall());
        StallCheck stallCheck1 = stallCheckMapper.selectOne(wrapper);
        if (stallCheck1!=null){
            throw  new AccountException(AccountExceptionCode.CARPORT_USE);
        }

        StallCheck stallCheck = new StallCheck();
        stallCheck.setRentersInfoId(param.getUserId());
        stallCheck.setCertifiedInfoId(param.getCertifiedInfoId());
        stallCheck.setStallInfoNum(param.getStall());
        stallCheck.setStallCheckNote(param.getNotes());
        stallCheck.setStallCheckState(StallInfoCode.STALL_WAITING_CHECK.getCode());
        stallCheck.setStallBuyProve(param.getImage());
        stallCheck.setRentersRealName(rentersInfoName);
        stallCheck.setRentersInfoCard(rentersInfoCard);
        stallCheckMapper.insert(stallCheck);
    }

    @Override
    public String uploadImage(MultipartFile image) throws IOException {
        //获取文件类型
        String fileType = FileTypeUtil.getType(image.getInputStream());
        if (!fileType.equals("jpg")&&!fileType.equals("png")){
            throw new CertifiedException(CertifiedExceptionCode.PICTURE_FORMAT_ERROR);
        }
        //创建文件名称
        Snowflake snowflake = new Snowflake(1,1);
        String prefix = snowflake.nextIdStr();
        String fileName = prefix+"."+fileType;
        String url = ossUtil.uploadFile(image.getInputStream(), fileName, "car-port");
        return url;
    }


    @Override
    public List<StallInfoDTO> renterGetStallByState(Integer renterId, Integer stateId) {
        StallInfoCode[] values = StallInfoCode.values();
        Boolean b=true;
        for (StallInfoCode stallInfoCode : values) {
            if (stallInfoCode.getCode()==stateId){
                b=false;
            }
        }
        if (b){
            throw new StallException(StallExceptionCode.STALL_STATE_NOT_HAVE);
        }
        Result<RentersInfo> rentersInfoResult = rentersClient.getRentersInfoById(renterId);
        RentersInfo rentersInfo = rentersInfoResult.getData();
        String stallInfoIdString = rentersInfo.getStallInfoId();
        JSONArray jsonArray = JSONUtil.parseArray(stallInfoIdString);
        List<Integer> stallInfoIds = jsonArray.toList(Integer.class);
        QueryWrapper<StallInfo> wrapper = new QueryWrapper<>();
        wrapper.in("stall_info_id",stallInfoIds);
        wrapper.eq("stall_use_state",stateId).or().eq("stall_up_down_state",stateId).or().eq("stall_check_state",stateId);
        List<StallInfo> stallInfos = stallInfoMapper.selectList(wrapper);
        List<StallInfoDTO> dtos=new ArrayList<StallInfoDTO>();
        Set<Integer> ids=new HashSet<>();
        for (StallInfo record : stallInfos) {
            Integer stallInfoId = record.getStallInfoId();
            ids.add(stallInfoId);
        }
        Result<List<OrderInfo>> listResult = orderClient.getOrderInfosByStallIds(ids);
        List<OrderInfo> orderInfoList = listResult.getData();
        for (StallInfo stallInfo : stallInfos) {
            Result<CertifiedInfo> certifiedInfoResult = certifiedClient.findCertifiedInfoById(stallInfo.getCertifiedInfoId());
            CertifiedInfo certifiedInfo = certifiedInfoResult.getData();
            String certifiedInfoName = certifiedInfo.getCertifiedInfoName();
            StallInfoDTO stallInfoDTO = BeanUtil.toBean(stallInfo, StallInfoDTO.class);
            for (OrderInfo orderInfo : orderInfoList) {
                if (orderInfo.getStatllInfoId()==stallInfo.getStallInfoId()){
                    LocalDateTime startTime = orderInfo.getStartTime();
                    LocalDateTime endTime = orderInfo.getEndTime();
                    LocalDateTime now = LocalDateTime.now();
                    if (now.isAfter(startTime)&&now.isBefore(endTime)){
                        stallInfoDTO.setStallUseState(StallInfoCode.STALL_ON_UES.getCode());
                        stallInfoDTO.setStateName(StallInfoCode.STALL_ON_UES.getMessage());
                        break;
                    }

                }
                stallInfoDTO.setStateName(StallInfoCode.STALL_ON_FREE.getMessage());
                stallInfoDTO.setStallUseState(StallInfoCode.STALL_ON_FREE.getCode());
            }
            for (StallInfoCode value : values) {
                if (value.getCode()== stallInfo.getStallUpDownState()){
                    stallInfoDTO.setUpDownStateName(value.getMessage());
                }
            }
            for (StallInfoCode value : values) {
                if (value.getCode()== stallInfo.getStallCheckState()){
                    stallInfoDTO.setCheckName(value.getMessage());
                }
            }
            stallInfoDTO.setCertifiedName(certifiedInfoName);
            StallTypeCode[] codes = StallTypeCode.values();
            for (StallTypeCode stallTypeCode : codes) {
                if (stallTypeCode.getCode()== stallInfo.getStallTpye()){
                    stallInfoDTO.setTypeName(stallTypeCode.getMessage());

                }
            }
            Integer id = stallInfoDTO.getStallInfoAffiliation();
            if (id==StallInfoCode.STALL_OF_CERTIFIED.getCode()){
                stallInfoDTO.setAffiliationName(StallInfoCode.STALL_OF_CERTIFIED.getMessage());
            }else {
                stallInfoDTO.setAffiliationName(StallInfoCode.STALL_OF_RENTER.getMessage());
            }

            dtos.add(stallInfoDTO);
        }
        return dtos;
    }

    @Override
    public List<StallInfoDTO> renterGetFreeStallByTime(Integer renterId, String startTime, String endTime) {
        Result<RentersInfo> rentersInfoResult = rentersClient.getRentersInfoById(renterId);
        RentersInfo rentersInfo = rentersInfoResult.getData();
        String stallInfoIdString = rentersInfo.getStallInfoId();
        JSONArray jsonArray = JSONUtil.parseArray(stallInfoIdString);
        List<Integer> stallInfoIds = jsonArray.toList(Integer.class);
        QueryWrapper<StallInfo> wrapper = new QueryWrapper<>();
        wrapper.in("stall_info_id",stallInfoIds);
        List<StallInfo> stallInfos = stallInfoMapper.selectList(wrapper);
        for (StallInfo stallInfo : stallInfos) {
            Integer stallInfoId = stallInfo.getStallInfoId();
            GetOrdersByStallIdAndTimeForm form = new GetOrdersByStallIdAndTimeForm();
            form.setStallId(stallInfoId);
            form.setEndTime(endTime);
            form.setStartTime(startTime);
            List<OrderInfo> list=orderClient.getOrdersByStallIdAndTime(form);
            if (list.size()!=0){
                stallInfos.remove(stallInfo);
            }
        }
        if (stallInfos.size()==0){
            throw new StallException(StallExceptionCode.STALL_CANT_USE);
        }
        StallInfoCode[] values = StallInfoCode.values();
        List<StallInfoDTO> dtos=new ArrayList<StallInfoDTO>();
        for (StallInfo stallInfo : stallInfos) {
            Result<CertifiedInfo> certifiedInfoResult = certifiedClient.findCertifiedInfoById(stallInfo.getCertifiedInfoId());
            CertifiedInfo certifiedInfo = certifiedInfoResult.getData();
            String certifiedInfoName = certifiedInfo.getCertifiedInfoName();
            StallInfoDTO stallInfoDTO = BeanUtil.toBean(stallInfo, StallInfoDTO.class);
            stallInfoDTO.setStateName(StallInfoCode.STALL_ON_FREE.getMessage());
            stallInfoDTO.setStallUseState(StallInfoCode.STALL_ON_FREE.getCode());
            for (StallInfoCode value : values) {
                if (value.getCode()== stallInfo.getStallUpDownState()){
                    stallInfoDTO.setUpDownStateName(value.getMessage());
                }
            }
            for (StallInfoCode value : values) {
                if (value.getCode()== stallInfo.getStallCheckState()){
                    stallInfoDTO.setCheckName(value.getMessage());
                }
            }
            stallInfoDTO.setCertifiedName(certifiedInfoName);
            StallTypeCode[] codes = StallTypeCode.values();
            for (StallTypeCode stallTypeCode : codes) {
                if (stallTypeCode.getCode()== stallInfo.getStallTpye()){
                    stallInfoDTO.setTypeName(stallTypeCode.getMessage());

                }
            }
            Integer id = stallInfoDTO.getStallInfoAffiliation();
            if (id==StallInfoCode.STALL_OF_CERTIFIED.getCode()){
                stallInfoDTO.setAffiliationName(StallInfoCode.STALL_OF_CERTIFIED.getMessage());
            }else {
                stallInfoDTO.setAffiliationName(StallInfoCode.STALL_OF_RENTER.getMessage());
            }

            dtos.add(stallInfoDTO);
        }
        return dtos;
    }
    @Override
    public List<StallCheck> loadAllstall(String id) {
        QueryWrapper<StallCheck> wrapper = new QueryWrapper<>();
        wrapper.eq("renters_info_id", id);
        List<StallCheck> stallChecks = stallCheckMapper.selectList(wrapper);
        return stallChecks;
    }

    @Override
    public PageInfo<StallCheck> loadAllstalls(LoadAllAccountParam param, String id) {
        Page<StallCheck> page = new Page<StallCheck>(param.getPageNum() == null ? 1 : param.getPageNum(), param.getPageSize() == null ? 5 : param.getPageSize());
        QueryWrapper<StallCheck> wrapper = new QueryWrapper<StallCheck>();
        wrapper.eq("renters_info_id",id);
        stallCheckMapper.selectPage(page, wrapper);
        PageInfo pageInfo = BeanUtil.toBean(page, PageInfo.class);
        pageInfo.setList(page.getRecords());
        pageInfo.setPages(page.getPages());
        System.out.println("----------------");
        System.out.println("----------------");
        System.out.println(pageInfo);
        System.out.println("PageInfo: ");
        System.out.println("List: " + pageInfo.getList());
        System.out.println("Pages: " + pageInfo.getPages());
        return pageInfo;
    }

    @Override
    public StallInfo loadcarportstatebyid(Integer stallInfoId) {
        System.out.println("-=-=-");
        System.out.println(stallInfoId);
        System.out.println("-=-=-");
        QueryWrapper<StallInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("stall_info_id",stallInfoId);
        StallInfo stallInfo = stallInfoMapper.selectOne(wrapper);
        return stallInfo;
    }

    @Override
    public List<StallInfoDTO> userGetCanUseStallsByTime(UserGetStallsByTimeParam param) {
        Integer certifiedInfoId = param.getCertifiedInfoId();
        String startTime = param.getStartTime();
        String endTime = param.getEndTime();
        boolean a = ObjectUtil.isEmpty(startTime);
        boolean b = ObjectUtil.isEmpty(endTime);
        if ((a&&!b)||(!a&&b)){
            throw new StallException(StallExceptionCode.CHOOSE_TIME_FIRST);
        }
        QueryWrapper<StallInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("certified_info_id",certifiedInfoId);
        wrapper.eq("stall_up_down_state",StallInfoCode.STALL_UP.getCode());
        List<StallInfo> stallInfos = stallInfoMapper.selectList(wrapper);
        for (StallInfo stallInfo : stallInfos) {
            Integer stallInfoId = stallInfo.getStallInfoId();
            GetOrdersByStallIdAndTimeForm form = new GetOrdersByStallIdAndTimeForm();
            form.setStallId(stallInfoId);
            form.setEndTime(endTime);
            form.setStartTime(startTime);
            List<OrderInfo> list=orderClient.getOrdersByStallIdAndTime(form);
            if (list.size()!=0){
                stallInfos.remove(stallInfo);
            }
        }
        if (stallInfos.size()==0){
            throw new StallException(StallExceptionCode.STALL_CANT_USE);
        }
        StallInfoCode[] values = StallInfoCode.values();
        List<StallInfoDTO> dtos=new ArrayList<>();
        for (StallInfo stallInfo : stallInfos) {
            Result<CertifiedInfo> certifiedInfoResult = certifiedClient.findCertifiedInfoById(stallInfo.getCertifiedInfoId());
            CertifiedInfo certifiedInfo = certifiedInfoResult.getData();
            String certifiedInfoName = certifiedInfo.getCertifiedInfoName();
            StallInfoDTO stallInfoDTO = BeanUtil.toBean(stallInfo, StallInfoDTO.class);
            stallInfoDTO.setStateName(StallInfoCode.STALL_ON_FREE.getMessage());
            stallInfoDTO.setStallUseState(StallInfoCode.STALL_ON_FREE.getCode());
            for (StallInfoCode value : values) {
                if (value.getCode()== stallInfo.getStallUpDownState()){
                    stallInfoDTO.setUpDownStateName(value.getMessage());
                }
            }
            for (StallInfoCode value : values) {
                if (value.getCode()== stallInfo.getStallCheckState()){
                    stallInfoDTO.setCheckName(value.getMessage());
                }
            }
            stallInfoDTO.setCertifiedName(certifiedInfoName);
            StallTypeCode[] codes = StallTypeCode.values();
            for (StallTypeCode stallTypeCode : codes) {
                if (stallTypeCode.getCode()== stallInfo.getStallTpye()){
                    stallInfoDTO.setTypeName(stallTypeCode.getMessage());

                }
            }
            Integer id = stallInfoDTO.getStallInfoAffiliation();
            if (id==StallInfoCode.STALL_OF_CERTIFIED.getCode()){
                stallInfoDTO.setAffiliationName(StallInfoCode.STALL_OF_CERTIFIED.getMessage());
            }else {
                stallInfoDTO.setAffiliationName(StallInfoCode.STALL_OF_RENTER.getMessage());
            }

            dtos.add(stallInfoDTO);
        }
        return dtos;
    }

    @Override
    public PageInfo<StallInfo> selectStallRentByCertifiedId(SelectStallRentByCertifiedIdParam param) {
        Page<StallInfo> page = new Page<>(param.getPageNum()==null?1:param.getPageNum(),param.getPageSize()==null?5:param.getPageSize());
        QueryWrapper<StallInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("stall_up_down_state",StallInfoCode.STALL_UP.getCode());
        stallInfoMapper.selectPage(page,wrapper);
        PageInfo pageInfo = BeanUtil.toBean(page, PageInfo.class);
        pageInfo.setList(page.getRecords());
        pageInfo.setTotal(page.getTotal());
        return pageInfo;
    }


}
